package com.d3works.apps.maintenance.db.repo;

import com.d3works.apps.base.db.Sequence;
import com.d3works.apps.base.service.administration.SequenceService;
import com.d3works.apps.maintenance.db.EquipementMaintenance;
import com.d3works.apps.maintenance.db.Imaintenance;
import com.d3works.apps.maintenance.exception.MaintenanceExceptionMessage;
import com.d3works.exception.D3worksException;
import com.d3works.exception.db.repo.TraceBackRepository;
import com.d3works.exception.service.TraceBackService;
import com.d3works.i18n.I18n;
import com.google.common.base.Strings;
import com.google.inject.Inject;
import javax.persistence.PersistenceException;

public class EquipementMaintenanceRepo extends EquipementMaintenanceRepository {

  @Inject private SequenceService sequenceService;

  @Override
  public EquipementMaintenance save(EquipementMaintenance entity) {
    try {
      if (Strings.isNullOrEmpty(entity.getCode())) {
        setCode(entity);
      }
      return super.save(entity);
    } catch (D3worksException e) {
      TraceBackService.traceExceptionFromSaveMethod(e);
      throw new PersistenceException(e.getMessage(), e);
    }
  }

  protected void setCode(EquipementMaintenance entity) throws D3worksException {
    String code =
        sequenceService.getSequenceNumber(
            Imaintenance.SEQ_MAINTENANCE, EquipementMaintenance.class, "code");

    if (Strings.isNullOrEmpty(code)) {
      throw new D3worksException(
          Sequence.class,
          TraceBackRepository.CATEGORY_NO_VALUE,
          I18n.get(MaintenanceExceptionMessage.EQUIPEMENT_MAINTENANCE_MISSING_SEQUENCE));
    }

    entity.setCode(code);
  }
}
